<!-- 编辑弹窗 -->
<template>
   <div class="ele-body">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px" >
      <el-card  >  
        <div slot="header" class="clearfix" style="display: flex;justify-content:space-between;" >
          <div style="width: 50%;" >基础信息</div>
          <div style="width: 50%;display: flex;justify-content:end;" >
            <div v-show="form.inOrderNo!='' && form.inOrderNo!=null" style="width: 30%;color:var(--color-primary)" >入库单号:{{ form.inOrderNo }}</div>
          </div>
        </div>      
        <el-row :gutter="24">
          <el-col :md="6" :sm="24" >
            <el-form-item label="入库日期:"  prop="inDate">
              <el-date-picker v-model="form.inDate" type="date" placeholder="请输入入库日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width:100%"  />
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24">
            <el-form-item label="经办人:" prop="operatorId">
              <el-select  v-model="form.operatorId" filterable placeholder="请选择制单人" style="width:100%" @change="selectoperate" >
                <el-option  v-for="item in accountDatas" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :md="6" :sm="24" >
            <el-form-item label="入库金额:"  >
              <el-input v-model="form.inAmount" disabled />
            </el-form-item>
          </el-col> -->
          <el-col :md="6" :sm="24" >
            <el-form-item label="费用明细合计:"  >
              <el-input v-model="form.clearAmount"   disabled/>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24" >
            <el-form-item label="费用明细合计:"  >
              <el-input v-model="form.clearAmountCn"   disabled  prefix-icon="el-icon-_rmb"  />
            </el-form-item>
          </el-col>
          <el-col :md="24" :sm="24" >
            <el-form-item label="备注:"  >
              <el-input :rows="2"
                  clearable
                  type="textarea"
                  :maxlength="200"
                  v-model="form.remark"
                  placeholder="请输入备注说明" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-card  style="margin-top: 10px">
        <div slot="header" class="clearfix" style="display: flex;justify-content:space-between;" >
          <div style="width: 8%;" >入库明细列表</div>
          <div style="width: 92%;display: flex;justify-content:start;" >
            <div style="width: 100%;color:var(--color-primary)" > 
                <el-button type="primary" class="ele-btn-icon" icon="el-icon-plus"  style="width: 13%;" @click="OpenProductList"  v-permission="'Inventory_Instock_PurOrderAdd'" >选择采购订单 </el-button>
              </div>
          </div>
        </div> 
        <!-- <el-tabs v-model="activeName">
          <el-tab-pane label="入库明细列表" name="first"> -->
            <el-table :data="form.items" ref="items"  :border="true" style="width: 100%" :height="tableHeight" :full-height="tableFullHeight" show-summary :summary-method="getSummaries"  :cell-style="cellStyle">
              <el-table-column type="index" width="50" align="center" label="序号" fixed='left' />
              <el-table-column label="订单号" width="150"  align="center">
                  <template slot-scope="{ row }">
                    <el-form-item label-width="10" style="margin-bottom:0;" >
                      <el-link type="primary" v-show="row.status!=5"  :underline="false"    @click="clickOrderNo(row)" >{{ row.purOrderNo }}</el-link>
                    </el-form-item>
                  </template>
              </el-table-column>
              <el-table-column label="产品编号" width="150"  prop="productCode" sortable  align="center">
                  <template slot-scope="{ row }">
                    <el-form-item label-width="10" style="margin-bottom:0;" >
                      <span>{{ row.productCode }}</span>
                    </el-form-item>
                  </template>
              </el-table-column>
              <el-table-column label="产品名称" width="150"  prop="productName" sortable  align="center">
                  <template slot-scope="{ row }">
                    <el-form-item label-width="10" style="margin-bottom:0;" >
                      <span>{{ row.productName }}</span>
                    </el-form-item>
                  </template>
              </el-table-column>
              <el-table-column label="规格" align="center"  width="100" >
                <template slot-scope="{ row }">
                  <span>{{ row.spc }}</span>
                </template>
              </el-table-column>
              <el-table-column label="单位" align="center"  width="100">
                  <template slot-scope="{ row }">
                      <span>{{ row.unitDesc }}</span>
                  </template>
              </el-table-column>
              <el-table-column label="应入数量" align="center" prop="purQty" sortable   width="120">
                  <template slot-scope="{ row }">
                      <span>{{ row.purQty }}</span>
                  </template>
              </el-table-column>
              <el-table-column label="入库数量" align="center"  prop="qty" sortable width="120">
                <template slot-scope="{ row ,$index}">
                  <el-form-item label-width="10" style="margin-bottom:0;" :prop="'items.'+ $index+'.qty'" :rules="itemRules.qty" >
                    <el-input  v-model="row.qty"  placeholder="请输入数量" @change="setAmount(row,$index)"  @keyup.native="row.qty = row.qty.replace(/[^\d.]/g,'');
                      row.qty = row.qty.replace(/\.{2,}/g,'.');
                      row.qty = row.qty.replace(/^\./g,'');
                      row.qty = row.qty.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                      row.qty = row.qty.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="应补数量" align="center" prop="actRepairQty" sortable   width="120">
                  <template slot-scope="{ row }">
                      <span>{{ row.actRepairQty }}</span>
                  </template>
              </el-table-column>
              <el-table-column label="已补数量" align="center" prop="repairQty" sortable   width="120">
                  <template slot-scope="{ row }">
                      <span>{{ row.repairQty }}</span>
                  </template>
              </el-table-column>
              <el-table-column label="成本单价(￥)" align="center"  prop="costPrice" sortable width="150">
                  <template slot-scope="{ row ,$index}">
                    <el-form-item label-width="10" style="margin-bottom:0;"  :prop="'items.'+ $index+'.costPrice'" :rules="itemRules.costPrice">
                      <el-input  v-model="row.costPrice"  placeholder="请输入成本单价"  @change="setAmount(row,$index)" @keyup.native="row.costPrice = row.costPrice.replace(/[^\d.]/g,'');
                      row.costPrice = row.costPrice.replace(/\.{2,}/g,'.');
                      row.costPrice = row.costPrice.replace(/^\./g,'');
                      row.costPrice = row.costPrice.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                      row.costPrice = row.costPrice.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/,'$1$2.$3');" />
                    </el-form-item>
                  </template>
              </el-table-column>
              <el-table-column label="应入金额" align="center"  prop="PurAmount" sortable width="120">
                <template slot-scope="{ row }">
                  <span>{{ row.PurAmount }}</span>
                </template>
              </el-table-column>
              <el-table-column label="入库金额" align="center"  prop="totalPrice" sortable width="120">
                <template slot-scope="{ row }">
                  <span>{{ row.totalPrice }}</span>
                </template>
              </el-table-column>
              <el-table-column label="应补金额" align="center"  prop="actRepairAmount" sortable width="120">
                <template slot-scope="{ row }">
                  <span>{{ row.actRepairAmount }}</span>
                </template>
              </el-table-column>
              <el-table-column label="已补金额" align="center"  prop="repairAmount" sortable width="120">
                <template slot-scope="{ row }">
                  <span>{{ row.repairAmount }}</span>
                </template>
              </el-table-column>
              <el-table-column label="集装箱号" align="center"  prop="containerNumber" sortable width="150">
                <template slot-scope="{ row, $index }">
                  <el-form-item label-width="10" style="margin-bottom:0;" :prop="'items.'+ $index+'.containerNumber'" :rules="itemRules.containerNumber" >
                    <el-input v-model="row.containerNumber" placeholder="请输入集装箱号" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="供应商" width="150"  prop="supplierId" sortable align="center">
                <template slot-scope="{ row }">
                  <el-form-item label-width="10" style="margin-bottom:0;" >
                    <el-select  filterable v-model="row.supplierId" class="ele-fluid"  disabled>
                      <el-option v-for="item in supplierDatas" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="仓库" align="center"  prop="wareHouseId" sortable width="150">
                <template slot-scope="{ row ,$index }">
                  <el-form-item label-width="10" style="margin-bottom:0;"   :prop="'items.'+ $index+'.wareHouseId'" :rules="itemRules.wareHouseId">
                    <el-select  filterable disabled v-model="row.wareHouseId" placeholder="请选择仓库" class="ele-fluid" >
                      <el-option v-for="item in wareHouseDatas" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="采购均摊" align="center"   sortable width="120" v-if="this.isUpdate ==3">
                <template slot-scope="{ row }">
                  <span>{{ row.purSharePriceTotal }}</span>
                </template>
              </el-table-column>
              <el-table-column label="清关均摊" align="center"  sortable width="120" v-if="this.isUpdate ==3">
                <template slot-scope="{ row }">
                  <span>{{ row.sharePriceTotal }}</span>
                </template>
              </el-table-column>
              <el-table-column label="行备注" align="center" width="250">
                <template slot-scope="{ row }">
                    <el-input  v-model="row.remarks" placeholder="请输入行备注" />
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" :resizable="false" v-if="form.status != 5" fixed='right' >
                <template slot-scope="{ row , $index}">
                  <span class="ele-action">
                    <el-link v-permission="'Inventory_Instock_PurOrderDel'" icon="el-icon-delete" type="danger" :underline="false" @click="remove(row, $index)" >删除</el-link>
                  </span>
                </template>
              </el-table-column>
            </el-table>
          <!-- </el-tab-pane>
          <el-tab-pane label="费用明细列表" name="second">
            <el-table :data="form.costs" ref="costs"  :border="true" style="width: 100%" :height="tableHeightFY" :full-height="tableFullHeightFY" >
              <el-table-column type="index" width="50" align="center" label="序号"   />
              <el-table-column label="费用名称" width="120" align="center" >
                  <template slot-scope="{ row }">
                    <el-form-item label-width="10" style="margin-bottom:0;" >
                      <span >{{ row.costDesc }}</span>
                    </el-form-item>
                  </template>
              </el-table-column>
              <el-table-column label="费用公司名称" width="200" align="center">
                <template slot-scope="{ row, $index}">
                  <el-form-item v-if="row.costNumber == 'C-FYLX03'" label-width="10"  style="margin-bottom:0;" :prop="'costs.'+ $index+'.supplierId'" :rules="(row.amount||row.rate)?costsRules.supplierId:costsRules.supplierIdIsNull">
                    <el-select  style="width: 100%;" filterable clearable v-model="row.supplierId" placeholder="请选择费用公司"  @change="(v)=>changeThreeCompany(row,v,$index)" >
                      <el-option  v-for="item in QGCompanyDatas" :key="item.id" :label="item.name" :value="item.id"/>
                    </el-select>
                  </el-form-item>

                  <el-form-item v-else-if="row.costNumber == 'C-FYLX04'" label-width="10"  style="margin-bottom:0;" :prop="'costs.'+ $index+'.supplierId'" :rules="(row.amount||row.rate)?costsRules.supplierId:costsRules.supplierIdIsNull">
                    <el-select  style="width: 100%;" filterable clearable v-model="row.supplierId" placeholder="请选择费用公司"  @change="(v)=>changeThreeCompany(row,v,$index)" >
                      <el-option  v-for="item in QTCompanyDatas" :key="item.id" :label="item.name" :value="item.id"/>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="币种" width="150" align="center">
                <template slot-scope="{ row, $index }">
                  <el-form-item label-width="10" style="margin-bottom:0;"  :prop="'costs.'+ $index+'.currencyId'" >
                    <el-select  filterable  v-model="row.currencyId" placeholder="请选择币种" class="ele-fluid" @change="(v)=>changeCurrency(v,$index)">
                      <el-option v-for="item in hbDatas" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="金额" width="150" align="center">
                  <template slot-scope="{ row, $index }">
                    <el-form-item label-width="10" style="margin-bottom:0;"  :prop="'costs.'+ $index+'.amount'" :rules="(row.supplierId||row.rate)?costsRules.amount:costsRules.amountIsNull">
                      <el-input v-model="row.amount" placeholder="请输入金额" @change="setExchangeAmount(row,$index)"  @keyup.native="row.amount = row.amount.replace(/[^\d.]/g,'');
                      row.amount = row.amount.replace(/\.{2,}/g,'.');
                      row.amount = row.amount.replace(/^\./g,'');
                      row.amount = row.amount.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                      row.amount = row.amount.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/,'$1$2.$3');"/>
                    </el-form-item>
                  </template>
              </el-table-column>
              <el-table-column label="汇率" width="150" align="center">
                <template slot-scope="{ row, $index }">
                  <el-form-item label-width="10" style="margin-bottom:0;" :prop="'costs.'+ $index+'.rate'" :rules="row.currencyCode!='C-HB01'&&(row.supplierId||row.amount)?costsRules.rate:costsRules.rateIsNull" >
                    <el-input v-if="row.currencyCode!='C-HB01'"   v-model="row.rate" placeholder="请输入汇率" :disabled="row.currencyCode=='C-HB01'" @change="setExchangeAmount(row,$index)"  @keyup.native="row.rate = row.rate.replace(/[^\d.]/g,'');
                        row.rate = row.rate.replace(/\.{4,}/g,'.');
                        row.rate = row.rate.replace(/^\./g,'');
                        row.rate = row.rate.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                        row.rate = row.rate.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/,'$1$2.$3');"/>
                    <span v-else>{{  row.rate }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="金额(￥)" width="150" align="center">
                  <template slot-scope="{ row  }">
                    <span>{{ row.amountCn }}</span>
                  </template>
              </el-table-column>
              <el-table-column label="行备注" align="center">
                <template slot-scope="{ row }">
                    <el-input v-model="row.remarks" placeholder="请输入行备注" />
                </template>
              </el-table-column>
            </el-table>
            <div class="right" style="display: flex;width: 100%;">
              <el-button type="warning" v-show="this.isUpdate!=3 && form.status!=5" @click="audit" v-permission="'Inventory_Instock_Audit'">
                审核
              </el-button>
              <el-button type="danger" v-show="form.status==5"  @click="unAudit"  v-permission="'Inventory_Instock_UnAudit'" >
                反审核
              </el-button>
            </div>
          </el-tab-pane>
        </el-tabs> -->
      </el-card>
      <el-card  style="margin-top: 10px">
        <div slot="header" class="clearfix" style="display: flex;justify-content:space-between;" >
          <div style="width: 8%;" >费用明细 </div>
          <div style="width: 92%;display: flex;justify-content:start;" >
            <div style="width: 100%;color:var(--color-primary)" > 
            </div>
          </div>
        </div> 
        <el-table :data="form.costs" ref="costs"  :border="true" style="width: 100%" >
          <el-table-column type="index" width="50" align="center" label="序号"   />
          <el-table-column label="费用名称" width="120" align="center" >
              <template slot-scope="{ row }">
                <el-form-item label-width="10" style="margin-bottom:0;" >
                  
                  <span >{{ row.costDesc }}</span>
                </el-form-item>
              </template>
          </el-table-column>
          <el-table-column label="费用公司名称" width="200" align="center">
            <template slot-scope="{ row, $index}">

              <el-form-item v-if="row.costNumber == 'C-FYLX03'" label-width="10"  style="margin-bottom:0;" :prop="'costs.'+ $index+'.supplierId'" :rules="(row.amount||row.rate)?costsRules.supplierId:costsRules.supplierIdIsNull">
                <el-select  style="width: 100%;" filterable clearable v-model="row.supplierId" placeholder="请选择费用公司"  @change="(v)=>changeThreeCompany(row,v,$index)" >
                  <el-option  v-for="item in QGCompanyDatas" :key="item.id" :label="item.name" :value="item.id"/>
                </el-select>
              </el-form-item>

              <el-form-item v-else-if="row.costNumber == 'C-FYLX04'" label-width="10"  style="margin-bottom:0;" :prop="'costs.'+ $index+'.supplierId'" :rules="(row.amount||row.rate)?costsRules.supplierId:costsRules.supplierIdIsNull">
                <el-select  style="width: 100%;" filterable clearable v-model="row.supplierId" placeholder="请选择费用公司"  @change="(v)=>changeThreeCompany(row,v,$index)" >
                  <el-option  v-for="item in QTCompanyDatas" :key="item.id" :label="item.name" :value="item.id"/>
                </el-select>
              </el-form-item>

            </template>
          </el-table-column>
          <el-table-column label="币种" width="150" align="center">
            <template slot-scope="{ row, $index }">
              <el-form-item label-width="10" style="margin-bottom:0;"  :prop="'costs.'+ $index+'.currencyId'" >
                <el-select  filterable  v-model="row.currencyId" placeholder="请选择币种" class="ele-fluid" @change="(v)=>changeCurrency(v,$index)">
                  <el-option v-for="item in hbDatas" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="金额" width="150" align="center">
              <template slot-scope="{ row, $index }">
                <el-form-item label-width="10" style="margin-bottom:0;"  :prop="'costs.'+ $index+'.amount'" :rules="(row.supplierId||row.rate)?costsRules.amount:costsRules.amountIsNull">
                  <el-input v-model="row.amount" placeholder="请输入金额" @change="setExchangeAmount(row,$index)"  @keyup.native="row.amount = row.amount.replace(/[^\d.]/g,'');
                  row.amount = row.amount.replace(/\.{2,}/g,'.');
                  row.amount = row.amount.replace(/^\./g,'');
                  row.amount = row.amount.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                  row.amount = row.amount.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/,'$1$2.$3');"/>
                </el-form-item>
              </template>
          </el-table-column>
          <el-table-column label="汇率" width="150" align="center">
            <template slot-scope="{ row, $index }">
              <el-form-item label-width="10" style="margin-bottom:0;" :prop="'costs.'+ $index+'.rate'" :rules="row.currencyCode!='C-HB01'&&(row.supplierId||row.amount)?costsRules.rate:costsRules.rateIsNull" >
                <el-input v-if="row.currencyCode!='C-HB01'"   v-model="row.rate" placeholder="请输入汇率" :disabled="row.currencyCode=='C-HB01'" @change="setExchangeAmount(row,$index)"  @keyup.native="row.rate = row.rate.replace(/[^\d.]/g,'');
                    row.rate = row.rate.replace(/\.{4,}/g,'.');
                    row.rate = row.rate.replace(/^\./g,'');
                    row.rate = row.rate.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                    row.rate = row.rate.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/,'$1$2.$3');"/>
                <span v-else>{{  row.rate }}</span>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="金额(￥)" width="150" align="center">
              <template slot-scope="{ row  }">
                <span>{{ row.amountCn }}</span>
                
              </template>
          </el-table-column>
          <el-table-column label="行备注" align="center">
            <template slot-scope="{ row }">
                <el-input v-model="row.remarks" placeholder="请输入行备注" />
            </template>
          </el-table-column>
        
        </el-table>
      </el-card>
      <el-card shadow="never"> </el-card>
    </el-form>
    <div  >
        <div class="ele-dailog-bottom" >
          <div class="left"  style="display: flex;width: 50%;">
          </div>
          <div class="right" style="display: flex;width: 32%;">
            <el-button type="primary" v-show="this.isUpdate!=3 && form.status!=5"  @click="save" v-permission="'Inventory_Instock_Save'">
            挂单
          </el-button>
          <el-button type="warning" v-show="this.isUpdate!=3 && form.status!=5" @click="audit" v-permission="'Inventory_Instock_Audit'">
            审核
          </el-button>
          <el-button type="danger" v-show="form.status==5"  @click="unAudit"  v-permission="'Inventory_Instock_UnAudit'" >
            反审核
          </el-button>
          <!-- <el-button type="info" @click="print" v-show="form.inOrderNo!='' && form.inOrderNo!=null">打印</el-button> -->
          <el-button  @click="handleClose">关闭</el-button>
          </div>
        </div>
      </div>
     <!-- 编辑弹窗 -->
     <purChooseList :visible.sync="showProductList"  @callback="reloadItemList"/>

     <costEdit :visible.sync="showAddCost"  @callback="reloadCostList" :data="current"/>
    </div>
  </template>
  <script>
   import { printHtml } from 'ele-admin';
   import costEdit from '../components/cost-edit.vue';
   import purChooseList from '../components/purchoose-list.vue';
   import { getUser } from '@/utils/user-util';
   import upload from "@/components/UpLoad/index.js";
   import { removePageTab, reloadPageTab,setPageTabTitle } from '@/utils/page-tab-util';
   import { GetAllAccount } from '@/api/usermanager/accountmanager';
   import { QueryModelByScurrencyId } from '@/api/basicdatamanager/ratemanager';
   import { GetAllWarehouse } from '@/api/basicdatamanager/warehousemanager';
   import { QueryAllChildDictViewByCode } from '@/api/systemmanager/dictmanager';
   import { GetAllBSupplier, QuerySupplierByType} from '@/api/basicdatamanager/supplier';
   import { AddInorder, UpdateInorder,QueryInorderById,AuitInorder,PrintInOrderById,AntiInorder } from '@/api/inventory/inorder';
  

    export default {
      name: 'InstockEdit',
      props: {
        // 弹窗是否打开
        visible: Boolean,
        // 修改回显的数据
        data: Object,
        // 按钮索引
        btnIndex:String,
      },
      mixins: [upload],
      components: {purChooseList,costEdit},
      data() {
        return {
          
          // 表单数据
          form: {id:'',createUser:'',createDate:'',items:[],costs:[],clearAmount:0,clearAmountCn:0},
          // 表单验证规则
          rules: {
            wareHouseId: [{required: true,message: '请选择收货仓',trigger: 'blur'}],
            deliveryDate: [{required: true,message: '请输入发货日期',trigger: 'blur'}],
            inDate: [{required: true,message: '请选择入库日期',trigger: 'blur'}],
            contractNumber: [{required: true,message: '请输入合同号',trigger: 'blur'}],
            operatorId:[{required: true,message: '请选择经办人',trigger: 'blur'}],
          },
          itemRules: {
            qty: [{required: true,message: '请输入数量',trigger: 'blur'}],
            costPrice: [{required: true,message: '请输入成本单价',trigger: 'blur'}],
            containerNumber: [{required: true,message: '请输入集装箱',trigger: 'blur'}],
            wareHouseId: [{required: true,message: '请输入入库仓库',trigger: 'blur'}],
          },
          costsRules: {
            amountIsNull: [{required: false}],
            rateIsNull: [{required: false}],
            currencyIdIsNull: [{required: false}],
            supplierIdIsNull: [{required: false}],
            
            amount: [{required: true,message: '请输入金额',trigger: 'blur'}],
            rate: [{required: true,message: '请输入汇率',trigger: 'blur'}],
            currencyId: [{required: true,message: '请输入币种',trigger: 'blur'}],
            supplierId: [{required: true,message: '请输入第三方公司',trigger: 'blur'}],
          },
          activeName:'first',
          fixedHeight:true,
          current:null,
          showAddCost:false,
          isShow:false,
          // 提交状态
          loading: false,
          // 是否是修改
          isUpdate: 1,
          inorderId:'',
          showProductList:false,
          defaultDate:new Date(),
          hbDatas:[],
          costDatas:[],
          accountDatas:[],
          supplierDatas:[],
          wareHouseDatas:[],
          QGCompanyDatas:[],
          QTCompanyDatas:[],
          computeDirection:2,//默认奈拉
        };
      },
      computed: {
        // 表格高度
        tableHeight() {

          var fh = this.fixedHeight ? 'calc(100vh - 380px)' : void 0;
          return fh;
        },
        // 表格全屏时高度
        tableFullHeight() {
          var fh =  this.fixedHeight ? 'calc(100vh - 280px)' : null;
          return fh;
        },

        // 表格高度
        tableHeightFY() {

          var fh = this.fixedHeight ? 'calc(100vh - 580px)' : void 0;
          return fh;
        },
        // 表格全屏时高度
        tableFullHeightFY() {
          var fh =  this.fixedHeight ? 'calc(100vh - 480px)' : null;
          return fh;
        },
      },
      
      //初始化数据
      mounted(){
        if(this.isUpdate == 2 || this.isUpdate == 3){
          this.setData(this.inorderId);
        }else if(this.isUpdate == 1){
          this.$refs['form'].clearValidate();
          this.form={id:'',items:[],costs:[],clearAmount:0,clearAmountCn:0};
          this.setData(this.Constant.DefaultCostsId);
        }
      },
      created(){
        this.initData();
        this.isUpdate = this.$route.query.isUpdate;
        this.inorderId = this.$route.query.inorderId;
        if(this.isUpdate == 1)  setPageTabTitle('添加入库单');
        if(this.isUpdate == 2)  setPageTabTitle('修改入库单');
        if(this.isUpdate == 3)  setPageTabTitle('查看入库单');
      },
      methods: {

        /* 初始化数据 */
        initData(){

          GetAllAccount().then((res)=>{
            this.accountDatas = [];
            this.accountDatas = res;
          });

          //清关费
          QuerySupplierByType(3).then((res)=>{
            this.QGCompanyDatas = [];
            this.QGCompanyDatas = res;
          });

          //其他费用 
          QuerySupplierByType(4).then((res)=>{
            this.QTCompanyDatas = [];
            this.QTCompanyDatas = res;
          });

          QueryAllChildDictViewByCode(this.Constant.C_HB).then((res)=>{
            this.hbDatas = [];
            this.hbDatas = res;
          });

          QueryAllChildDictViewByCode(this.Constant.C_FYLX).then((res)=>{
            this.costDatas = [];
            this.costDatas = res;
          });

          GetAllWarehouse().then((res)=>{
            this.wareHouseDatas = [];
            this.wareHouseDatas = res;
          });

          GetAllBSupplier().then((res)=>{
            this.supplierDatas = [];
            this.supplierDatas = res;
          });
        },

        save() {
          //校验必填信息
          this.$refs['form'].validate((valid) => {
            if (!valid) {return false;}

            
           var qty = this.form.items.reduce((pre,cur)=> { return parseFloat(pre?pre:0 ) +  parseFloat(cur.qty?cur.qty:0 ) },0);
           var purqty =  this.form.items.reduce((pre,cur)=> { return parseFloat(pre?pre:0 ) +  parseFloat(cur.purQty?cur.purQty:0 ) },0);


           if(qty>purqty){
            this.$message.error("入库数据不能大于应入数量");
            return;
           }

            this.setSharePrice();
            this.form.inOrderType = 1; //采购入库

            this.loading = true;
            const saveOrUpdate = this.isUpdate ==2 ? UpdateInorder : AddInorder;
            saveOrUpdate(this.form)
              .then((msg) => {
                this.loading = false;
                this.$message.success(msg);
                this.updateVisible();
              })
              .catch((e) => {
                this.loading = false;
                this.$message.error(e.message);
              });
          });
        },

        /* 审核入库单 */
        audit(){
          //校验必填信息
          this.$refs['form'].validate((valid) => {
            if (!valid) {return false;}

            if(this.form.items==null || this.form.items==undefined || this.form.items.length==0){
              this.$message.info('产品列表不能为空');
              return;
            }

            this.setSharePrice();

            this.loading = true;
            this.form.inOrderType = 1; //采购入库
            AuitInorder(this.form)
              .then((msg) => {
                this.loading = false;
                this.$message.success(msg);
                this.updateVisible();
              })
              .catch((e) => {
                this.loading = false;
                this.$message.error(e.message);
              });
          });
        },

        unAudit(){
          this.loading = true;
          AntiInorder(this.form.id)
            .then((msg) => {
              this.loading = false;
              this.$message.success(msg);
              this.updateVisible();
            })
            .catch((e) => {
              this.loading = false;
              this.$message.error(e.message);
            });
        },

        
        //费用分摊
        //A产品采购金额10元
        //B产品采购金额20元
        //A/B产品总共产生了6元的运费
        //那么A产品分摊6÷（10+20）×10=2元
        //B产品分摊6÷（10+20）×20=4元
        setSharePrice(){
          var amount = 0
          var costAmountcn = 0;
          var inamount =this.form.inAmount? parseFloat(this.form.inAmount):0;

          if(this.form.costs!=null && this.form.costs!=undefined){
            costAmountcn =  this.form.costs.reduce((pre,cur)=> { return parseFloat(pre?pre:0 ) +  parseFloat(cur.amountCn?cur.amountCn:0 ) },0);
          }

          if(this.form.items!=null && this.form.items!=undefined){
            amount = costAmountcn/inamount;
            this.form.items.map((item,index)=>{
              var amounttotal = amount * item.totalPrice;
              this.form.items[index].sharePrice = parseFloat(item.qty)<=0?0:(amounttotal/parseFloat(item.qty)).toFixed(4);
            })
          }
        },


        setData(id){
          QueryInorderById(id)
            .then((res) => {
              this.form = res; 
              this.setCostRequired(0);

              if(id == this.Constant.DefaultCostsId){
                let currentUser = getUser();
                this.$set(this.form,'inDate',this.defaultDate);
                this.$set(this.form,'operatorId',currentUser.accountId);
                this.$set(this.form,'operatorName',currentUser.accountName);
              }
              
              this.$nextTick(() => {
                this.$refs.items.doLayout();
              });
          });
        },

        selectoperate(val){
          let acc = this.accountDatas.find((v)=>{ return v.id == val });
          if(acc){
            this.form.operatorName = acc.name;
          }
        },

        OpenProductList(){
          this.showProductList =true;
        },

        reloadItemList(orderData){

          this.form.items = [];

          orderData.map((item)=>{
            this.form.items.push({
              purOrderId:item.purOrderId,
              purOrderNo:item.purOrderNo,
              inOrderId:this.form.id,
              productId:item.productId,
              unitId:item.unitId,
              qty:item.qty,
              purQty:item.qty,
              awaitQty:0,
              repairQty:0,
              actRepairQty:0,
              PurAmount:item.qty*item.costPrice,
              actRepairAmount:0,
              repairAmount:0,
              costPrice:item.costPrice,
              totalPrice:item.totalPrice,
              sharePrice:item.sharePrice,
              sharePriceTotal:item.sharePriceTotal,
              purSharePrice:item.purSharePrice,
              wareHouseId:item.wareHouseId,
              containerNumber:item.containerNumber,
              wareHouseDesc:item.wareHouseDesc,
              productCode:item.productCode,
              productName:item.productName,
              spc:item.spc,
              unitDesc:item.unitDesc,
              supplierId:item.supplierId,
              purItemId:item.purItemId,
              repairInOrderItemId:item.repairInOrderItemId,
              repairInOrderId:item.repairInOrderId,
            })
          });

          this.$nextTick(() => {
            this.$refs.items.doLayout();
          });

          this.setPurAmountTotal();
        },

        //
        reloadCostList(cost){
          if(cost){
            this.form.costs = [];
            this.form.costs.push(cost);
            this.form.clearAmount = cost.amount;
          }else{
            QueryInorderById(this.form.id).then((d)=>{
              this.form.costs = [];
              this.form.costs = d.costs;
              this.form.clearAmount = d.clearAmount;
            });

            this.$nextTick(() => {
              this.$refs.costs.doLayout();
            });
          }
        },

        changeCurrency(val,index){
          let hb = this.hbDatas.find((p)=>p.id === val)
          if(hb){
           this.$refs.costs.data[index].currencyCode = hb.code;
           if(hb.code == 'C-HB01'){
              this.$refs.costs.data[index].rate = 1;
              this.$refs.costs.data[index].amountCn = this.$refs.costs.data[index].amount;
           }else{
            QueryModelByScurrencyId(val).then((res)=>{

              this.$refs.costs.data[index].rate =res? res.rate:1;
              this.$refs.costs.data[index].amountCn = (res?res.computeDirection:1) ==1?(this.$refs.costs.data[index].amount * res.rate ).toFixed(4):(this.$refs.costs.data[index].amount / res.rate ).toFixed(4);
            })
           }
          }

          this.setCostRequired(index);
        },

        setCostRequired(index){

          if(this.form.costs){
            if(this.form.costs[index].amount>0 || this.form.costs[index].rate>0||(this.form.costs[index].currencyId!=''&&this.form.costs[index].currencyId!=null) || (this.form.costs[index].supplierId!=''&&this.form.costs[index].supplierId!=null)){

              this.costsRules.amount = [{required: true,message: '请输入金额',trigger: 'blur'}];
              this.costsRules.rate = [{required: true,message: '请输入汇率',trigger: 'blur'}];
              this.costsRules.currencyId = [{required: true,message: '请输入币种',trigger: 'blur'}];
              this.costsRules.supplierId = [{required: true,message: '请输入第三方公司',trigger: 'blur'}];

              }else{
              this.costsRules.amount = null;
              this.costsRules.rate = null;
              this.costsRules.currencyId = null;
              this.costsRules.supplierId = null;

            }
          }
        },
       
        //选择第三方公司
        changeThreeCompany(row,val,index){

          if(row.costNumber == 'C-FYLX03'){
            let qgCompany = this.QGCompanyDatas.find((p)=>p.id === val)
            if(qgCompany){
              this.$refs.costs.data[index].rate = qgCompany.rate;
              this.$refs.costs.data[index].currencyId = qgCompany.currencyId;
              this.$refs.costs.data[index].supplierTypeId = qgCompany.typeId;
              this.changeCurrency(qgCompany.currencyId,index);
            }
          }else if(row.costNumber == 'C-FYLX04'){
            let qtCompany = this.QTCompanyDatas.find((p)=>p.id === val)
            if(qtCompany){
              this.$refs.costs.data[index].rate = qtCompany.rate;
              this.$refs.costs.data[index].currencyId = qtCompany.currencyId;
              this.$refs.costs.data[index].supplierTypeId = qtCompany.typeId;
              this.changeCurrency(qtCompany.currencyId,index);
            }
          }
          
          this.setCostRequired(index);
        },

        //设置金额
        setAmount(row,index){

          if(row.qty==null || row.qty==''){
            row.qty== 0;
          }

          if(row.qty > row.purQty){
            this.$message.info("入库数据不能大于采购数量");
            return;
          }

          row.actRepairQty =  row.purQty -  row.qty ;

          if(row.costPrice){
              let qty = parseFloat(row.qty);
              let purQty = parseFloat(row.purQty);
              let actRepairQty = parseFloat(row.actRepairQty);
              
              let costPrice = parseFloat(row.costPrice);
              this.$refs.items.data[index].totalPrice = (costPrice * qty).toFixed(4);
              this.$refs.items.data[index].PurAmount = (costPrice * purQty).toFixed(4);
              this.$refs.items.data[index].actRepairAmount = (costPrice * actRepairQty).toFixed(4);
          }

          this.setPurAmountTotal();
        },

        //设置入库金额
        setPurAmountTotal(){
          this.form.inAmount = 0;
          if(this.form.items!=null && this.form.items!=undefined && this.form.items.length>0){
            this.form.qtyTotal = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.qty) },0);
            this.form.inAmount = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.totalPrice) },0);

            this.form.purAmount = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.PurAmount?cur.PurAmount:0) },0);
            this.form.actRepairAmount = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.actRepairAmount?cur.actRepairAmount:0) },0);
            this.form.repairAmount = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.repairAmount?cur.repairAmount:0) },0);

            this.form.qtyTotal =this.form.qtyTotal.toFixed(2);
            this.form.inAmount =this.form.inAmount.toFixed(4);
            this.form.purAmount =this.form.purAmount.toFixed(4);
            this.form.repairAmount =this.form.repairAmount.toFixed(4);
            this.form.actRepairAmount =this.form.actRepairAmount.toFixed(4);
          }
        },

        setExchangeAmount(row,index){
          this.form.clearAmount = 0;
          this.form.clearAmountCn = 0;
          if(row.amount && row.rate){
              let rate = parseFloat(row.rate);
              let amount = parseFloat(row.amount);
              // if(row.costNumber =='C-FYLX03')this.form.clearAmount = amount;  //港杂费
              if(row.currencyCode == 'C-HB01'){
                this.$refs.costs.data[index].rate =1;
                this.$refs.costs.data[index].amountCn = amount;
              }else{
                this.$refs.costs.data[index].amountCn = (amount/rate).toFixed(4);
                QueryModelByScurrencyId(row.currencyId).then((res)=>{
                  if(res){
                    this.$refs.costs.data[index].amountCn = res.computeDirection == 1? (amount*rate).toFixed(4): (amount/rate).toFixed(4);
                  }
                })
              }
          }

          if(this.form.costs!=null && this.form.costs!=undefined && this.form.costs.length>0){
            this.form.clearAmount = this.form.costs.reduce((pre,cur)=> { return parseFloat(pre?pre:0)  + parseFloat( cur.amount?cur.amount:0) },0);
            this.form.clearAmount = this.form.clearAmount.toFixed(4);

            this.form.clearAmountCn = this.form.costs.reduce((pre,cur)=> { return parseFloat(pre?pre:0)  + parseFloat( cur.amountCn?cur.amountCn:0) },0);
            this.form.clearAmountCn = this.form.clearAmountCn.toFixed(4);
          }

          this.setCostRequired(index);
        },

        /* 删除 */
        remove(_row, index) {
          // this.form.items.splice(index, 1);
          this.form.items = this.form.items.filter((c)=>{return c.productCode !=_row.productCode && c.productName != _row.productName});
          this.setPurAmountTotal();
        },

        /* 删除 */
        removeCost(_row, index) {
          this.form.costs.splice(index, 1);
        },
     
        /* 更新visible */
        updateVisible() {
          removePageTab({ key: this.$route.path });
          reloadPageTab({ fullPath: '/invoicingmanager/instockmanager' });
        },

        handleClose() {
          removePageTab({ key: this.$route.path });
          this.$router.push('/invoicingmanager/instockmanager');
        },

        clickOrderNo(row){
          removePageTab({ key: '/businesshandling/purordermanager' });
          this.$nextTick(() => {
            this.$router.push({path: '/businesshandling/purordermanager', query: { "billNo": row.purOrderNo } });
          });
        },

        AddCost(isadd){
          this.showAddCost =true;
          this.current = this.form.costs?this.form.costs[0]:{} ;
          if(!this.current)this.current = {};
          this.current.isAdd = isadd;
          this.current.inOrderId = this.form.id;
        },

        /* 合计 */
        getSummaries(param){
          const sums = [];
          sums[0] = '合计' ;
          const { columns, data } = param;
          columns.forEach((column, index) => {
            if(index ==7){
              sums[index] = Number(this.form.qtyTotal).toFixed(4);
            }else if(index ==11){
              sums[index] = Number(this.form.purAmount).toFixed(4);
            }else if(index ==12){
              sums[index] = Number(this.form.inAmount).toFixed(4);
            }else if(index ==13){
              sums[index] = Number(this.form.actRepairAmount).toFixed(4);
            }else if(index ==14){
              sums[index] = Number(this.form.repairAmount).toFixed(4);
            }
          });

          this.$nextTick(() => {
            this.$refs.items.doLayout();
          });
          return sums;
        },

        /* 样式 */
        cellStyle(param){
          const { row, column, rowIndex, columnIndex } = param;
          if(columnIndex==6||columnIndex==8){
            return{
              color:''
            }
          }
        },

        // 打印
        print(){
          PrintInOrderById(this.form.id).then((data)=>{
            const pWindow = printHtml({
              html: data, // 要打印的内容
              // style: '<style>span { color: red; }</style>',  // 页面样式
              // title: '', // 页面标题，浏览器打印设置显示页眉会显示页面标题
              horizontal: true, // 是否横向打印
              blank: true, // 是否打开新页面打印
              close: true, // 如果是打开新页面，打印完是否关闭
              print: true, // 如果是打开新窗口是否自动打印
              iePreview: true, // 是否兼容 ie 打印预览
              loading: true, // 是否显示 loading
              before: () => { // 打印开始的回调
              },
              done: () => { // 打印完成的回调
              },
              margin: 0, // 页间距
              header: '', // 页眉 html
              footer: '' // 页脚 html
            });
          });
        },
    },
     
      /* 监听visible属性变化 */
      watch: {
        visible(visible) {
         
          if (visible) {
            if (this.data && this.data.id) {
              //赋值this.form
              this.setData(this.data.id);
              this.isUpdate = this.data.id !=null && this.data.id !=undefined;
            } else {
              this.form={id:'',costs:[],clearAmount:0,clearAmountCn:0};
              this.isUpdate = false;
              let currentUser = getUser();
              this.$set(this.form,'inDate',this.defaultDate);
              this.$set(this.form,'operatorId',currentUser.accountId);
              this.$set(this.form,'operatorName',currentUser.accountName);
            }
          } else {
              this.$refs['form'].clearValidate();
              this.form = {id:'',costs:[],clearAmount:0,clearAmountCn:0};
              let currentUser = getUser();
              this.form.operatorId = currentUser.accountId;
              this.form.inDate = this.defaultDate;
          }
        }
      }
    };
  </script>
  <style lang="scss" scoped>
  /*总计字体颜色
  ::v-deep .el-table__footer-wrapper tbody td {
     color: var(--color-primary);
     cursor: pointer;
   }*/
 </style>